package com.training.admin.web.controller.data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.entity.page.Page;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.persistence.support.QueryOrder;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.demo2do.core.web.resolver.Preloading;
import com.demo2do.core.web.utils.WebUtils;
import com.training.admin.entity.category.TrainingCategory;
import com.training.admin.entity.search.TrainingCategorySearch;
import com.training.admin.service.TrainingCategoryService;

/**
 * 
 * @author Rockett
 * 
 */
@Controller
@RequestMapping("/training-categories")
@MenuSetting("menu-system-management")
public class TrainingCategoryController {
	private static final Logger logger = LoggerFactory.getLogger(TrainingCategoryController.class);

    @Autowired
    private TrainingCategoryService trainingCategoryService;
	
	/**
	 * 列表页
	 * @return
	 */
	@RequestMapping(value = "", method = RequestMethod.GET)
	@MenuSetting("submenu-training-category-management")
	public ModelAndView list(Page page) {
		ModelAndView modelAndView = new ModelAndView("training-category/training-category-list");
		int totals = trainingCategoryService.count(TrainingCategory.class);
		
		List<TrainingCategory> trainingCategoryList = trainingCategoryService.listByPage(TrainingCategory.class,new QueryOrder("id", "ASC"),page.with(totals));
		Map<Long,String> categoryMap = new HashMap<Long,String>();
        List<Long> parentIds = new ArrayList<Long>();
		for(int i=0;i<trainingCategoryList.size();i++){
			categoryMap.put(trainingCategoryList.get(i).getId(), trainingCategoryList.get(i).getName());
			if(trainingCategoryList.get(i).getParentId()!=null && !parentIds.contains(trainingCategoryList.get(i).getParentId()) ){
				parentIds.add(trainingCategoryList.get(i).getParentId());
			}
		}
		//put the parent obj into Map
		for(int i=0;i<parentIds.size();i++){
			if(parentIds.get(i)==null || categoryMap.containsKey(parentIds.get(i))){
				continue;
			}
			TrainingCategory parentCategory = trainingCategoryService.load(TrainingCategory.class, parentIds.get(i));
			if(parentCategory!=null && parentCategory.getId()!=null){
				categoryMap.put(parentCategory.getId(), parentCategory.getName());
    		}
		}

		page.calculate();
		modelAndView.addObject("trainingCategories", trainingCategoryList);
		modelAndView.addObject("categoryMap", categoryMap);
		modelAndView.addObject("page", page);
		return modelAndView;
	}
	
    /**
     * onSearch
     * 
     * @param accountSearch
     * @param page
     * @param request
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET, params = "filter")
    @MenuSetting("submenu-training-category-management")
    public ModelAndView onSearch(TrainingCategorySearch trainingCategorySearch, Page page, HttpServletRequest request) {

        ModelAndView modelAndView = new ModelAndView("training-category/training-category-list");

        int totals = trainingCategoryService.count(TrainingCategory.class, trainingCategorySearch.getFilter());
        if(totals > 0){

            List<TrainingCategory> trainingCategoryList = trainingCategoryService.search(TrainingCategory.class, trainingCategorySearch, page.with(totals));
    		
            
            Map<Long,String> categoryMap = new HashMap<Long,String>();
            List<Long> parentIds = new ArrayList<Long>();
    		for(int i=0;i<trainingCategoryList.size();i++){
    			categoryMap.put(trainingCategoryList.get(i).getId(), trainingCategoryList.get(i).getName());
    			if(trainingCategoryList.get(i).getParentId()!=null && !parentIds.contains(trainingCategoryList.get(i).getParentId()) ){
    				parentIds.add(trainingCategoryList.get(i).getParentId());
    			}
    		}	

    		//put the parent obj into Map
    		for(int i=0;i<parentIds.size();i++){
    			if(parentIds.get(i)==null || categoryMap.containsKey(parentIds.get(i))){
    				continue;
    			}
    			TrainingCategory parentCategory = trainingCategoryService.load(TrainingCategory.class, parentIds.get(i));
    			if(parentCategory!=null && parentCategory.getId()!=null){
    				categoryMap.put(parentCategory.getId(), parentCategory.getName());
        		}
    		}
    		
    		
            modelAndView.addObject("trainingCategories", trainingCategoryList);
    		modelAndView.addObject("categoryMap", categoryMap);
            modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page", "filter"));
            
        }

        return modelAndView;
        
    }	
	

	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@MenuSetting("submenu-training-category-management")
	public ModelAndView view() {
		ModelAndView modelAndView = new ModelAndView("training-category/training-category-view");
		return modelAndView;
	}

	@RequestMapping(value = "/search", method = RequestMethod.GET)
	@MenuSetting("submenu-training-category-management")
	public ModelAndView search() {
		ModelAndView modelAndView = new ModelAndView("training-category/training-category-search");
		List<TrainingCategory> trainingCategoryList =trainingCategoryService.listAllFirstCategory();
		modelAndView.addObject("firstCategories", trainingCategoryList);

		return modelAndView;
	}

	
	/**
	 * 修改一级分类
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}/first-edit", method = RequestMethod.GET)
	@MenuSetting("submenu-training-category-management")
	public ModelAndView editFirstCategory(@PathVariable("id") Long id) {
		ModelAndView modelAndView = new ModelAndView("training-category/first-category-edit");
		TrainingCategory trainingCategory =trainingCategoryService.load(TrainingCategory.class, id);
		modelAndView.addObject("trainingCategory", trainingCategory);
		return modelAndView;
	}
	/**
	 * 修改二级分类
	 * @return
	 */
	@RequestMapping(value = "/{id}/second-edit", method = RequestMethod.GET)
	@MenuSetting("submenu-training-category-management")
	public ModelAndView editSecondCategory(@PathVariable("id") Long id) {
		ModelAndView modelAndView = new ModelAndView("training-category/second-category-edit");
		TrainingCategory trainingCategory =trainingCategoryService.load(TrainingCategory.class, id);
		List<TrainingCategory> trainingCategoryList =trainingCategoryService.listAllFirstCategory();
		modelAndView.addObject("firstCategories", trainingCategoryList);
		modelAndView.addObject("trainingCategory", trainingCategory);
		return modelAndView;
	}
	/**
	 * 修改提交
	 * @param trainingCategory
	 * @return
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@MenuSetting("submenu-training-category-management")
	public @ResponseBody HttpResult onEdit(@Preloading("trainingCategoryId") TrainingCategory trainingCategory) {

		HttpResult httpResult = new HttpResult();
      try {
        	trainingCategoryService.update(trainingCategory);
            
            httpResult.success().message("修改分类成功！");
        	
		} catch (Exception e) {
			httpResult.fail("500").message("修改分类失败! " + e.getMessage());
			logger.error("#onEdit() - update training category fail, exception is [{}]", e);
		}
        
        return httpResult;

	}
	/**
	 * 修改提交
	 * @param trainingCategory
	 * @return
	 */
	@RequestMapping(value = "/{id}/delete", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@MenuSetting("submenu-training-category-management")
	public @ResponseBody HttpResult onDelete(@Preloading("trainingCategoryId") TrainingCategory trainingCategory) {

		HttpResult httpResult = new HttpResult();
      try {
    	  	trainingCategory.setDisabled(true);
        	trainingCategoryService.update(trainingCategory);
            
            httpResult.success().message("删除分类成功！");
        	
		} catch (Exception e) {
			httpResult.fail("500").message("删除分类失败! " + e.getMessage());
			logger.error("#ondelete() - delete training category fail, exception is [{}]", e);
		}
        
        return httpResult;

	}

	@SuppressWarnings("rawtypes")
    @RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
	@MenuSetting("submenu-training-category-management")
	public ModelAndView disable(@PathVariable("id") Long id) {
		ModelAndView modelAndView = new ModelAndView("training-category/training-category-delete");
		TrainingCategory trainingCategory =trainingCategoryService.load(TrainingCategory.class, id);
		 boolean canDelete = true;
		if(trainingCategory.getParentId()!=null){
			TrainingCategory parentCategory =trainingCategoryService.load(TrainingCategory.class, trainingCategory.getParentId());
			modelAndView.addObject("parentCategory", parentCategory);
		}else{
			//检查是否有子分类，有则不能删除
			List childrenCategoryList = trainingCategoryService.listByFirstCategoryId(trainingCategory.getId());
			if (childrenCategoryList!=null&& childrenCategoryList.size()>0){
				canDelete=false;
			}
		}
		
		modelAndView.addObject("canDelete", canDelete);
		modelAndView.addObject("trainingCategory", trainingCategory);
		return modelAndView;
	}
	
	/**
	 * 
	 * @return
	 */
	@RequestMapping(value = "/first-create", method = RequestMethod.GET)
	@MenuSetting("submenu-training-category-management")
	public ModelAndView createFirstCategory() {
		ModelAndView modelAndView = new ModelAndView("training-category/first-category-create");
		return modelAndView;
	}
	
	/**
	 * 
	 * @param id
	 * @return
	 */
	@SuppressWarnings("unused")
    @RequestMapping(value = "/{id}/second-create", method = RequestMethod.GET)
	@MenuSetting("submenu-training-category-management")
	public ModelAndView createSecondCategory(@PathVariable Long id) {
		ModelAndView modelAndView = new ModelAndView("training-category/second-category-create");
		List<TrainingCategory> trainingCategoryList =trainingCategoryService.listAllFirstCategory();
		TrainingCategory trainingCategory = trainingCategoryService.load(TrainingCategory.class, id);
		
		modelAndView.addObject("trainingCategory", trainingCategory);
		return modelAndView;
	}

	/**
	 * 新增一级分类提交
	 * 
	 * @return
	 */
	@RequestMapping(value = "", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@MenuSetting("submenu-training-category-management")
	public  @ResponseBody HttpResult onCreate(TrainingCategory TrainingCategory) {
		
        HttpResult httpResult = new HttpResult();
        
        
        try {

    		trainingCategoryService.save(TrainingCategory);
            
            httpResult.success().message("创建分类成功！");
        	
		} catch (Exception e) {
			httpResult.fail("500").message("创建分类失败! " + e.getMessage());
			logger.error("#onCreate() - create category fail, exception is [{}]", e);
		}
        
        return httpResult;

	}
	
}
